<script setup lang="ts">
import {
  HeartOutlined,
  UserOutlined,
  RocketOutlined,
  MessageOutlined,
  SearchOutlined, createFromIconfontCN
} from '@ant-design/icons-vue'
import {loginConfigStore} from "@/store/user/loginConfigStore";
import {computed, onBeforeMount, ref} from "vue";
import {userConfigStore} from "@/store/user/userConfigStore";
import {getListByDictTypeList} from "@/api/system/sysDict";
import {defaultSummary, ECode, iconFontAddress, PagePath} from "@/util/commonUtil";
import {useSystemDictStore} from "@/store/system/systemDictStore";
import _ from "lodash";
import {delCookie, getCookie} from "@/util/cookieUtil";
import {deleteUserAccessToken, getCurrentUserAmount} from "@/api/user/user";
import {message} from "ant-design-vue";
import {cookieToken} from "@/config/CookieConfig";
import {router} from "@/router";
import HeaderDrawer from "@/components/header/drawer/index.vue"

onBeforeMount(async () => {
  // 获取系统字典
  await getDictList()
})
const userAmount = ref<number>(0)
// 引入阿里图标库
const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
});

const drawer = ref<boolean>(false)

function handleClick() {
  loginConfigStore().setLoginMessage(Math.random())
}

const isLogin: any = computed(() => userConfigStore().isLogin)
const userInfo: any = computed(() => userConfigStore().userInfo)
// 用户等级图片字典
const userLevelImagesDictList = ref<any>([])

function getUserAmountMethod(){
  getCurrentUserAmount().then((res: any) => {
    if (res.code === ECode.SUCCESS){
      userAmount.value = res.data
    }
  })
}
// 获取系统字典
async function getDictList() {
  let dictTypeList = [
    "sys_yes_no",
    "sys_user_sex",
    "sys_user_tag",
    "sys_feedback_status",
    "sys_editor_modal",
    "sys_content_report_type",
    "sys_original_status",
    "sys_publish_status",
    "sys_audit_status",
    "sys_normal_disable",
    "sys_medal_type",
    "user_level_images",
    'sys_user_level'
  ];
  await getListByDictTypeList(dictTypeList).then((response: any) => {
    if (response.code == ECode.SUCCESS) {
      let dictMap = response.data;
      userLevelImagesDictList.value = dictMap.user_level_images.list;
      // 设置全局状态
      useSystemDictStore().UserLevelImages = dictMap.user_level_images.list;
      useSystemDictStore().SysYesNo = dictMap.sys_yes_no.list;
      useSystemDictStore().SysUserSex = dictMap.sys_user_sex.list;
      useSystemDictStore().SysUserTag = dictMap.sys_user_tag.list;
      useSystemDictStore().SysFeedbackStatus = dictMap.sys_feedback_status.list;
      useSystemDictStore().SysEditorModal = dictMap.sys_editor_modal.list;
      useSystemDictStore().SysContentReportType = dictMap.sys_content_report_type.list;
      useSystemDictStore().SysOriginalStatus = dictMap.sys_original_status.list;
      useSystemDictStore().SysPublishStatus = dictMap.sys_publish_status.list;
      useSystemDictStore().SysAuditStatus = dictMap.sys_audit_status.list;
      useSystemDictStore().SysNormalDisable = dictMap.sys_normal_disable.list;
      useSystemDictStore().SysMedalType = dictMap.sys_medal_type.list;
      useSystemDictStore().SysUserLevel = dictMap.sys_user_level.list;
    }
  })
}

function getLvImage(level: any) {
  if (_.isEmpty(userLevelImagesDictList.value)) {
    return;
  }
  return userLevelImagesDictList.value[level - 1].dictValue;
}

async function userLogout() {
  await deleteUserAccessToken(getCookie(cookieToken)).then((res: any) => {
    if (res.code == ECode.SUCCESS) {
      delCookie(cookieToken);
      if (localStorage.getItem(cookieToken)){
        localStorage.removeItem(cookieToken)
      }
      message.success("退出成功!");
    }
  }).finally(() => {
    window.location.reload();
  });
}

function handleCommand(command: string) {
  // todo 后面补全功能
  switch (command){
    case "goUserInfo":{
      drawer.value = true
      getUserAmountMethod()
    }break
    case "goUserCenter": {
      const routeData = router.resolve({
        path: PagePath.UserCenterPath,
        query: { userUid: userInfo.value.uid },
      });
      window.open(routeData.href, '_blank')
    }break
    case "vip": {
      const routeData = router.resolve({
        path: PagePath.Vip,
      })
      window.open(routeData.href, '_blank')
    }break
    case "medal": {
      const routeData = router.resolve({
        path: PagePath.MedalPath + userInfo.value.uid,
      })
      window.open(routeData.href, '_blank')
    }break
  }
}
function drawerEmit(e:boolean){
  drawer.value = e
}
</script>

<template>
  <div class="header-avatar relative cursor-pointer">
    <a-dropdown placement="bottom" v-if="!isLogin">
      <a-avatar size="large" class="h-8 w-8">
        <template #icon>
          <UserOutlined/>
        </template>
      </a-avatar>
      <template #overlay>
        <a-menu>
          <a-menu-item key="desc">
            <a-row :gutter="[16,16]" style="width: 240px;">
              <a-col :span="12">
                <HeartOutlined/>
                收藏有用内容
              </a-col>
              <a-col :span="12">
                <SearchOutlined/>
                阅读优质专栏
              </a-col>
              <a-col :span="12">
                <MessageOutlined/>
                进行评论互动
              </a-col>
              <a-col :span="12">
                <RocketOutlined/>
                提升成长等级
              </a-col>
              <a-col :span="24">
                <a-button type="primary" class="w-full" @click="handleClick">立即登录</a-button>
              </a-col>
            </a-row>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <!-- 登录成功展示 -->
    <a-dropdown placement="bottom" v-if="isLogin">
      <div class="relative">
        <a-avatar v-if="userInfo.photoUrl" size="large" class="h-8 w-8" :src="userInfo.photoUrl"
                  style="border: var(--vip-border)"/>
        <a-avatar v-else size="large" class="h-8 w-8 flex items-center justify-center">
          {{ userInfo.nickName.slice(0, 1) }}
        </a-avatar>
        <sub class="badgeSup h-4 w-4 absolute -bottom-1 -right-1" v-if="userInfo.userTag > 0">
          <img src="@/assets/vip/vip.svg" class="h-full w-full" alt="vipBadge">
        </sub>
      </div>
      <template #overlay>
        <a-menu>
          <a-menu-item key="desc" style="width: var(--user-panel);padding: 1rem var(--user-panel-padding)">
            <a-row :gutter="[16,16]">
              <!-- 下拉菜单头像 -->
              <a-col :span="5">
                <div class="relative">
                  <a-avatar v-if="userInfo.photoUrl" size="large" class="h-10 w-10" :src="userInfo.photoUrl"
                            style="border: var(--vip-border)"/>
                  <a-avatar v-else size="large" class="h-10 w-10 flex items-center justify-center"
                            style="border: var(--vip-border)">
                    {{ userInfo.nickName.slice(0, 1) }}
                  </a-avatar>
                  <sub class="badgeSup h-4 w-4 absolute -bottom-1 -right-1" v-if="userInfo.userTag > 0">
                    <img src="@/assets/vip/vip.svg" class="h-full w-full" alt="vipBadge">
                  </sub>
                </div>
              </a-col>
              <!-- 下拉菜单用户信息 -->
              <a-col :span="18" v-if="userInfo">
                <div class="flex items-center gap-2">
                  <span class="text-[14px] overflow-hidden font-semibold line-clamp-1"
                        :class="userInfo.userTag>0?'text-rose-500':''">
                  {{ userInfo.nickName }}
                  </span>
                  <span class="userGender">
                    <IconFont type="icon-nanxing" v-if="userInfo.gender == '1'"/>
                    <IconFont type="icon-nv" v-else-if="userInfo.gender == '2'"/>
                    <IconFont type="icon-nannv" v-else/>
                  </span>
                  <span class="userLevel h-5 w-auto" v-if="userInfo.userLevel">
                    <img class="w-full h-full" :src="getLvImage(userInfo.userLevel)" alt="userLevel">
                  </span>
                </div>
                <div class="summary mt-0.5" v-if="userInfo">
                  <span class="text-gray-400 text-[12px] line-clamp-1">{{
                      userInfo.summary ? userInfo.summary : defaultSummary
                    }}</span>
                </div>
              </a-col>
            </a-row>
            <!-- 下拉菜单操作面板 -->
            <a-row :gutter="[16,16]" class="flex justify-between mt-4">
              <a-col :span="10">
                <div class="userCenter flex gap-1.5 hover:text-rose-500" @click="handleCommand('goUserInfo')">
                  <UserOutlined/>
                  <span>个人中心</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="UserInfo flex gap-1.5 hover:text-rose-500" @click="handleCommand('goUserCenter')">
                  <IconFont type="icon-wodezhuye"/>
                  <span>我的主页</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="userPost flex gap-1.5 hover:text-rose-500" @click="handleCommand('article')">
                  <IconFont type="icon-wodewenzhang"/>
                  <span>我的文章</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="userMedal flex gap-1.5 hover:text-rose-500" @click="handleCommand('medal')">
                  <IconFont type="icon-xunzhang"/>
                  <span>我的勋章</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="userCollect flex gap-1.5 hover:text-rose-500" @click="handleCommand('myCollect')">
                  <HeartOutlined/>
                  <span>我的收藏</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="vipCenter flex gap-1.5 hover:text-rose-500" @click="handleCommand('vip')">
                  <IconFont type="icon-huiyuan" class="text-[16px]"/>
                  <span>会员中心</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="accountBind flex gap-1.5 hover:text-rose-500" @click="handleCommand('bind')">
                  <IconFont type="icon-account-binding"/>
                  <span>账号绑定</span>
                </div>
              </a-col>
              <a-col :span="10">
                <div class="openApi flex gap-1.5 hover:text-rose-500" @click="handleCommand('openapi')">
                  <IconFont type="icon-APIjiechu-APIOut" class="text-[16px]"/>
                  <span>调用服务</span>
                </div>
              </a-col>
            </a-row>
            <a-divider class="mt-2.5 mb-2.5" style="border-color: #7cb305" dashed/>
            <div class="flex w-full justify-center">
              <a-button @click="userLogout">退出登录</a-button>
            </div>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <HeaderDrawer
        :drawer-show="drawer"
        :user="userInfo"
        :userAmount="userAmount"
        @closeDrawer="drawerEmit"/>
  </div>
</template>

<style scoped lang="less">
:deep(.ant-dropdown-menu-item:hover) {
  background-color: #fff !important;
  box-shadow: none;
}
</style>
